import 'package:flutter/material.dart';

///无状态控件StatelessWidget,无状态控件从父控件接受参数,以final成员变量存储,当一个控件被build时,
///它使用这些存储的值作为创建控件的参数
///为了构建更友好的体验,比如以更有趣的方式对用户的输入做出相应,应用通常会有一些状态.
///Flutter使用StatefulWidget实现这个想法,可以保持状态

void main() {
  runApp(MaterialApp(
    title: 'Flutter教程02-2',
    home: Counter(),
  ));
}

class CounterDisplay extends StatelessWidget {
  final int count;

  CounterDisplay({this.count});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('按钮点击$count次'),
    );
  }
}

class CounterIncrementor extends StatelessWidget {
  final VoidCallback onPressed;

  CounterIncrementor({this.onPressed});

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton(
      onPressed: onPressed,
      tooltip: '增加',
      child: Icon(Icons.add),
    );
  }
}

class Counter extends StatefulWidget {
  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _count = 0;

  void _increment() {
    setState(() {
      //每点击一次,触发一次修改状态的方法,从而重新build一次当前控件
      _count += 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter实例02-3'),
      ),
      body: CounterDisplay(
        count: _count,
      ),
      floatingActionButton: CounterIncrementor(
        onPressed: _increment,
      ),
    );
  }
}
